﻿@Code
    
    Dim id = UrlData(0).AsInt()
    Dim db = Database.Open("CalibreDB")
    Dim path = db.QuerySingle("SELECT path FROM books WHERE books.id = @0", id)
    If path Is Nothing Then
        Response.SetStatus(HttpStatusCode.NotFound)
        Return
    End If
    
    Dim CalibreLib As String = ConfigurationManager.AppSettings("CalibreLib").ToString
    Dim strpath = CalibreLib & path.path.ToString() & "\cover.jpg"
    strpath = Replace(strpath, "/", "\")

    Dim cover() As Byte = File.ReadAllBytes(strpath)
    
    Dim img = New WebImage(New MemoryStream(CType(cover, System.Byte())))

    Dim t = UrlData(1)

    Dim h As Integer = img.Height
    Dim w As Integer = img.Width
    Dim Ratio As Decimal
    Dim MaxWidthThumb As Integer = 256
    Dim MaxHeightThumb As Integer = 256
    Dim MaxWidthNormal As Integer = 512
    Dim MaxHeightNormal As Integer = 512
    Dim NewWidth As Integer
    Dim NewHeight As Integer
        
    Select Case t
        Case "0"
                
            Ratio = Convert.ToDecimal(MaxHeightThumb / img.Height)
            NewHeight = MaxHeightThumb
            NewWidth = 220

        Case "1"
            If (img.Width > img.Height) Then
                Ratio = Convert.ToDecimal(MaxWidthThumb / img.Width)
                NewWidth = MaxWidthThumb

                Dim Temp As Decimal = img.Height * Ratio
                NewHeight = Convert.ToInt32(Temp)
            Else
                Ratio = Convert.ToDecimal(MaxHeightThumb / img.Height)
                NewHeight = MaxHeightThumb

                Dim Temp As Decimal = img.Width * Ratio
                NewWidth = Convert.ToInt32(Temp)
                'If NewWidth < 220 Then NewWidth = 220
            End If
                

        Case Else
            If (img.Width > img.Height) Then
                Ratio = Convert.ToDecimal(MaxWidthNormal / img.Width)
                NewWidth = MaxWidthNormal

                Dim Temp As Decimal = img.Height * Ratio
                NewHeight = Convert.ToInt32(Temp)
            Else
                Ratio = Convert.ToDecimal(MaxHeightNormal / img.Height)
                NewHeight = MaxHeightNormal

                Dim Temp As Decimal = img.Width * Ratio
                NewWidth = Convert.ToInt32(Temp)
            End If

    End Select
    
    Dim size = If(Request("size"), "")

    Select Case size.ToUpperInvariant()
        Case "SMALL"
            NewWidth = 200
            NewHeight = 200
        Case "MEDIUM"
            NewWidth = 400
            NewHeight = 300
        Case "LARGE"
            NewWidth = 625
            NewHeight = 625
        Case Else
            'Response.SetStatus(HttpStatusCode.BadRequest)
            'Return
    End Select
    
    img.Resize(NewWidth, NewHeight).Write()
   
End Code





